from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from model.ModWorkRecord import WorkRecord, workRecordSchema
from database import Session, engine
import datetime
from dao import DaoWorkRecord
import uuid


class WorkRecordCheck(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
           bureauid = request.query_params["bureauid"]
           #stationid = request.query_params["stationid"]
           flag = request.query_params["flag"]   # 1待确认记录  2已确认未抄回记录
           return DaoWorkRecord.get_workrecord_list(session, bureauid, flag)
        finally:
            session.close()

    async def put(self, request):
        session = Session()
        try:
            dict_work = await request.json()
            message_str = ""
            initial_result_flag = ""
            final_result_flag = ""
            work_department = ""
            serial_number = dict_work.get("serial_number")
            if len(dict_work.get("initial_result_flag")) > 0:
                initial_result_flag = dict_work.get("initial_result_flag")
                final_result_flag = dict_work.get("initial_result_flag")
            else:
                message_str = message_str + "处理结果、"
            if len(dict_work.get("work_department")) > 0:
                work_department = dict_work.get("work_department")
            else:
                message_str = message_str + "处理方"
            if len(message_str) > 0:
                last_str = message_str[-1]
                if last_str == "、":
                    message_str = message_str[:-1]
                message_str = "请确认：" + message_str + "等信息是否填写完整！"
                return JSONResponse({"result": "2", "message_str": message_str})
            remark = dict_work.get("remark")
            confirm_openid = request.user.open_id
            confirm_openname = request.user.display_name
            DaoWorkRecord.update_workrecord_info(session, serial_number, initial_result_flag, final_result_flag, work_department,confirm_openid,confirm_openname,remark)
            session.commit()
        except Exception as e:
            session.rollback()
            return JSONResponse({"result": "0"})
        else:
            return JSONResponse({"result": "1"})
        finally:
            session.close()

class WorkRecordCheckCount(HTTPEndpoint):
    async def get(self, request):
        session = Session()
        try:
           bureauid = request.query_params["bureauid"]
           cou=DaoWorkRecord.get_pending_count(session, bureauid)
           return JSONResponse({"result": cou})
        finally:
            session.close()